package com.dr.controller;

import java.util.List;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.dr.pojo.Dept;
import com.dr.pojo.User;
import com.dr.service.DeptService;
import com.dr.service.UserService;

@Controller
@RequestMapping("/um")
public class UserController { 
	@Autowired
	private UserService userService;//Spring注入ServiceImpl的实例
	
	@Autowired
	private DeptService deptService;//Spring注入ServiceImpl的实例
	
	@RequestMapping("/userList")
	public ModelAndView userList(User user) {
		List<User> userList = userService.findUserList(); //取得用户列表数据
//		for(User user : list){
//			List<Dept> deptList = deptService.findDeptByName(user.getDeptId());
//		}
		ModelAndView mav = new ModelAndView();
		mav.addObject("userList", userList); //向页面传数据,相当于request.setAttribute("userList", uesrList)
		mav.setViewName("userManage/userList.jsp");
		
		return mav;
	}
	
	@RequestMapping("/userListByName")
	public ModelAndView userListByName(String txtQuery) {
		List<User> userList = userService.findUserByName(txtQuery); //
		ModelAndView mav = new ModelAndView();
		mav.addObject("userList", userList); //
		mav.setViewName("userManage/userList.jsp");
		
		return mav;
	}
	
	@RequestMapping("/toAdd")
	public ModelAndView toAdd() {
		ModelAndView mav = new ModelAndView();
		List<Dept> deptList = deptService.findDeptList();
		mav.addObject("deptList", deptList); 
		mav.setViewName("userManage/userAdd.jsp");		
		return mav;
	}
	
	@RequestMapping("/doAdd")
	public ModelAndView doAdd(User user,HttpSession session) {	
		String account = user.getAccount();
		User addUser = userService.findUserByAccount(account);
		
		if(addUser!=null) {
			//账户存在
			ModelAndView mav = toAdd();
			mav.addObject("attrInfoUserAdd","账户已存在");
			return mav;
		}
		else {
			//账户不存在
			userService.insertUser(user,session);
			return userList(user);
		}
	
	}
	
	@RequestMapping("/toUpdate")
	public ModelAndView toUpdate(Integer id,HttpSession session) {
		ModelAndView mav = new ModelAndView();
		List<Dept> deptList = deptService.findDeptList();
		User user = userService.findUserById(id);
		mav.addObject("deptList", deptList); 
		mav.addObject("user", user); 
		mav.setViewName("userManage/userUpdate.jsp");		
		return mav;
	}
	
	@RequestMapping("/doUpdate")
	public ModelAndView doUpdate(User user,HttpSession session) {	
			//System.out.println(user);
			userService.updateUser(user,session);
			return userList(user);

	}
	@RequestMapping("/doDelete")
	public ModelAndView doDelete(User user,HttpSession session) {	
			//System.out.println(user);
			userService.deleteUser(user,session);
			return userList(user);

	}
}
